/**
 * email: 1418154909@qq.com
 * author:fanjiantao
 */
const Webpack = require("webpack");
const qrcode = require("qrcode-terminal");
const os = require("os");
const fs = require("fs");
const { resolve } = require("path");
const autoprefixer = require("autoprefixer");
const pxtorem = require("postcss-pxtorem");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const webpack = require("webpack");
const WebpackBar = require("webpackbar");
const projectConfig = require("./project.config");
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const AddAssetHtmlPlugin = require("add-asset-html-webpack-plugin");
//将在dll中生成很多不同的第三方包，在通过DllReferencePlugin，AddAssetHtmlPlugin这两个插件引入到项目的js/html文件中，需要额外设置
const files = fs.readdirSync(resolve(__dirname, "./dist/dll/vendor"));
//用于存储DllReferencePlugin插件的配置，只能引入对象
const dllReferenceFiles = [];
//用于存储AddAssetHtmlPlugin插件的配置，
const contentBase = {};
if (!IS_PROD) {
	contentBase.contentBase = "./dist";
}
let extracts = [];
if (IS_PROD) {
	//extracts=["selectDep"];//忽略提取的css项目用来处理单独的lib
}
console.log(resolve(__dirname, "./dist/dll/vendor").replace("\\", "/"));
const htmlAssetFiles = [];
files.forEach((file) => {
	if (/.*\.js$/.test(file)) {
		console.log(file);
		htmlAssetFiles.push({
			filepath: resolve(__dirname, "./dist/dll/vendor", file),
			publicPath: "../dll/vendor",
			outputPath: "../dll/vendor",
		});
	}

	if (/.*\.manifest.json$/.test(file)) {
		dllReferenceFiles.push({ manifest: resolve(__dirname, "./dist/dll/vendor", file) });
	}
});

const { say } = require("cfonts");
const chalk = require("chalk");
function getLocalIP() {
	const interfaces = os.networkInterfaces();
	for (const devName in interfaces) {
		const iface = interfaces[devName];
		for (let i = 0; i < iface.length; i++) {
			const alias = iface[i];
			console.log(alias);
			if (
				alias.family === "IPv4" &&
				alias.address !== "127.0.0.1" &&
				!alias.internal &&
				alias.address.indexOf("192.") > -1
			) {
				return alias.address;
			}
		}
	}
	return null;
}

say("APP-vue2.x-template", {
	colors: ["yellow"],
	font: "simple",
	space: false,
});
console.log("生产环境：", IS_PROD);
console.log(chalk.yellow.bold(process.env.IS_ANALY ? "开始分析分析依赖" : "\n"));

function addStyleResource(rule) {
	rule
		.use("style-resource")
		.loader("style-resources-loader")
		.options({
			patterns: [path.resolve(__dirname, "./src/assets/less/var.less")],
		});
}
let projectName = process.env.PROJECT_NAME;
console.log(projectConfig[projectName]);
console.log(chalk.red.bold("编译项目名称：" + projectName + "\n"));
module.exports = {
	parallel: require("os").cpus().length > 1,
	publicPath: "./",
	transpileDependencies: [],
	lintOnSave: false,
	productionSourceMap: false,
	outputDir: "dist/" + projectName + "/",
	...projectConfig[projectName],
	// pages: {
	//     index: {
	//         entry: "src/pages/list/main.js",
	//         template: "src/pages/list/public/index.html",
	//         title: "列表页",
	//         filename: "list.html",
	//         // chunks: ['chunk-vendors', 'chunk-common', 'index']
	//     },
	//     detail: {
	//         entry: "src/pages/detail/main.js",
	//         template: "src/pages/detail/public/index.html",
	//         title: "详情页",
	//         // chunks: ['chunk-vendors', 'chunk-common', 'index']
	//     },
	// },
	css: {
		extract: !extracts.includes(projectName),
		loaderOptions: {
			postcss: {
				plugins: [
					autoprefixer(),
					// pxtorem({
					//     // rootValue: 37.5,
					//     rootValue({ file }) {
					//         //设计稿比例设置
					//         return file.indexOf('vant') !== -1 ? 37.5 : 37.5;
					//         // return file.indexOf('vant')!==-1
					//     },
					//     propList: ['*']
					// })
				],
			},
		},
	},
	chainWebpack: (config) => {
		config.resolve.alias.set("@", path.join(__dirname, "./src"));
		config.stats = "none";
		const types = ["vue-modules", "vue", "normal-modules", "normal"];
		types.forEach((type) => addStyleResource(config.module.rule("less").oneOf(type)));
		config.optimization.minimizer("terser").tap((args) => {
			args[0].terserOptions.compress.drop_console = true;
			return args;
		});

		if (process.env.IS_ANALY) {
			config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
				{
					analyzerMode: "static",
				},
			]);
		}
		IS_PROD &&
			config
				.plugin("banner")
				.use(Webpack.BannerPlugin, [
					`太蓝app h5 \n email:1418154909@qq.com \n author:fanjiantao \n time: ${new Date()} \n version: beta v1.01`,
				])
				.end();
		// if (IS_PROD) {
		//     config.optimization.delete('splitChunks')
		// }
		return config;
	},
	configureWebpack: {
		// output: {
		//       libraryExport: 'default'
		// },

		stats: {
			assets: false,
		},
		// resolve: {
		//     alias: {
		//       '#util$': path.resolve(__dirname, './src/util/index.js'),
		//     }
		//   },
		plugins: [
			new CopyWebpackPlugin([
				{
					from: path.resolve(__dirname, "src/staticProject/electronic"),
					to: path.resolve(__dirname, "./dist/"),
				},
			]),
			// new webpack.DllReferencePlugin({
			//     context: process.cwd(),
			//     manifest: require(path.resolve(__dirname, './dist/dll/vendor/vendor-manifest.json'))
			// }),
			// 将 dll 注入到 生成的 html 模板中
			// (!IS_PROD && new AddAssetHtmlPlugin({
			//     // dll文件位置
			//     filepath: path.resolve(__dirname, './dist/dll/vendor/*.js'),
			//     // dll 引用路径
			//     publicPath: "./dll/vendor",
			//     // // dll最终输出的目录
			//     outputPath: "./dll/vendor"
			// }) || function() {}),
			// /**开发环境提取出来**/
			// (IS_PROD && new AddAssetHtmlPlugin({
			//     // dll文件位置
			//     filepath: path.resolve(__dirname, './dist/dll/vendor/*.js'),
			//     // dll 引用路径
			//     //publicPath: "../dll/vendor",
			//     // // dll最终输出的目录
			//     outputPath: "../dll/vendor",
			// }) || function() {}),
			...dllReferenceFiles.map((obj) => new webpack.DllReferencePlugin(obj)),
			new AddAssetHtmlPlugin(htmlAssetFiles),
			(IS_PROD &&
				new WebpackBar({
					name: `app vue2.x 配置`, //配置加载进度
				})) ||
				function() {},
			//非lib入口 文件全局注入
			process.env.provide == "false"
				? function() {
						console.log(process.env.provide);
				  }
				: new webpack.ProvidePlugin({
						axiosHttp: [path.resolve(__dirname, `src/lib/axiosHttp.js`), "default"],
						$commonApi: [path.resolve(__dirname, `src/api/commonApi.js`), "default"],
						$api: [path.resolve(__dirname, `src/projects/${projectName}/api/index.js`), "default"],
						// manba: "manba",
						// $: "jQuery",
				  }),
			function(compiler) {
				compiler.hooks.done.tap("complete", (stats) => {
					// console.log("构建耗时", (new Date().getTime() - startDate) / 1000 + "s");
					// setTimeout(() => {
					//     console.log(qrcode.generate(`http://${getLocalIP()}:8080/createFlow.html`, {
					//         small: true,
					//         width: 100,
					//         height: 100,
					//     }));
					//     console.log("构建耗时", (new Date().getTime() - startDate) / 1000 + "s");
					// })
				});
			},
		],
		// optimization: {
		//     splitChunks: {
		//         cacheGroups: {
		//             vueBase: {
		//                 name: 'vueBase',
		//                 test: /[\\/]node_modules[\\/]_?[vue|vuex|axios](.*)/,
		//                 chunks: 'initial',
		//                 priority: -10,
		//             },
		//             common: {
		//                 name: 'common',
		//                 chunks: 'initial',
		//                 priority: -20,
		//                 minChunks: 2,
		//             }
		//         }
		//     }
		// }
	},

	// pluginOptions: { // 第三方插件配置
	//     'style-resources-loader': {
	//         preProcessor: 'less',
	//         patterns: [path.resolve(__dirname, './src/assets/less/var.less')] // less所在文件路径
	//     }
	// }
	devServer: {
		...contentBase,
		inline: true,
		// before: function(app, server, compiler) {
		//     console.log(arguments)
		//         // app.get('/some/path', function (req, res) {
		//         //   res.json({ custom: 'response' });
		//         // });
		// },
		//compress: true,
		// proxy: {
		//     "/": {
		//         target: "http://192.168.10.143:2828", // 目标代理接口地址
		//         changeOrigin: true, // 开启代理，在本地创建一个虚拟服务端
		//         // ws: true, // 是否启用websockets
		//         pathRewrite: {
		//             "^/": "/"
		//         },
		//         onProxyReq(proxyReq, req, res) {

		//             // proxyReq.setHeader('cookie', 'cto_lwid=9ba20fdd-9cb4-4de5-a9c2-6a85d8a8654365465a8e9;');
		//         }
		//     },
		// }
	},
};
